package com.example.webservice_client;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.io.UnsupportedEncodingException;
/**
 * @author: wzq
 * @date: 14-8-1
 * description: 类说明
 */
public class WeatherWs extends Activity {
    private final String NAMESPACE = "http://WebXml.com.cn/";
    private final String URL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
    private final String METHOD_NAME = "getWeatherbyCityName";
    private final String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";

    private String weatherToday;
    private SoapObject detail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather);

        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    public void run() {
                        getWeather("广州");
                    }
                }.start();
            }
        });
    }

    public void getWeather(String cityName) {
        try {
            SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);
            System.out.println("rpc " + rpc);
            System.out.println("cityName is " + cityName);
            rpc.addProperty("theCityName", cityName);
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.bodyOut = rpc;
            envelope.dotNet = true;
            envelope.setOutputSoapObject(rpc);
            HttpTransportSE ht = new HttpTransportSE(URL);
            ht.debug = true;
            ht.call(SOAP_ACTION, envelope);
            Object obj = envelope.getResponse();
            detail = (SoapObject)obj;
            //System.out.println("detail=" + detail);
            parseWeather(detail);

            return;
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void parseWeather(SoapObject detail) throws UnsupportedEncodingException {
        String date = detail.getProperty(6).toString();
        weatherToday = "今天：" + date.split(" ")[0];
        weatherToday = weatherToday + "\n天气：" + date.split(" ")[1];
        weatherToday = weatherToday + "\n气温：" + detail.getProperty(5).toString();
        weatherToday = weatherToday + "\n风力：" + detail.getProperty(7).toString() + "\n";
        System.out.println("weatherToday is " + weatherToday);
    }
}
